package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: exchange
 * @author: chanzhugang
 * @create: 2022/10/19 00:02
 */
public class Exchange {

    /**
     * 剑指offer 21 调整数组顺序使奇数位于偶数前面
     * https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
     *
     * @param nums
     * @return
     */
    public int[] exchange(int[] nums) {
        // 奇数在前，偶数在后
        // 前后双指针，交换位置
        int i = 0;
        int j = nums.length - 1;
        while (i < j) {
            if (nums[i] % 2 == 1) {
                i++;
                continue;
            }
            if (nums[j] % 2 == 0) {
                j--;
                continue;
            }
            // 交换奇偶
            swap(nums, i, j);
            i++;
            j--;
        }
        return nums;
    }


    public int[] exchange2(int[] nums) {
        // 双指针 + 开辟新数组
        int n = nums.length;
        int[] arr = new int[n];
        int i = 0;
        int j = n - 1;
        for (int k = 0; k < n; k++) {
            if (nums[k] % 2 == 1) {
                arr[i++] = nums[k];
            } else {
                arr[j--] = nums[k];
            }
        }
        return arr;
    }


    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}